package com.light.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.light.common.pojo.ESPojo;
import com.light.gulimall.search.constant.ESConstants;
import com.light.gulimall.search.dto.SearchDTO;
import com.light.gulimall.search.service.SearchService;
import com.light.gulimall.search.vo.SearchVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {


    @Autowired
    private RestHighLevelClient client;

    /**
     * 商品上架后信息保存在es->根据前端传递的搜索条件构建dsl去es中搜索->解析并封装查询结果给前端页面
     * @param searchDTO 条件
     * @return
     */
    @Override
    public SearchVO searchForCondition(SearchDTO searchDTO) {
        //构建查询请求
        SearchRequest searchRequest = this.getSearchRequest(searchDTO);
        SearchVO vo;
        try {
            //查询
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            System.out.println("返回的结果"+searchResponse.toString());
            //解析查询结果，封装成SearchVO
            vo = this.parseSearchRequest(searchResponse,searchDTO);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return vo;
    }

    private SearchVO parseSearchRequest(SearchResponse resp, SearchDTO searchDTO) {
        SearchVO vo = new SearchVO();
        //外层hits
        SearchHits hits = resp.getHits();
        //里层hits
        SearchHit[] hitsArr = hits.getHits();

        List<ESPojo> esPojos = Arrays.stream(hitsArr).map(searchHit -> {
            //_source
            String sourceAsString = searchHit.getSourceAsString();
            ESPojo esPojo = JSON.parseObject(sourceAsString, ESPojo.class);
            //判断是否按关键字检索，若是就显示高亮，否则不显示
            if (!StringUtils.isEmpty(searchDTO.getKeyword())) {
                //拿到高亮信息显示标题
                HighlightField skuTitle = searchHit.getHighlightFields().get("skuTitle");
                String skuTitleValue = skuTitle.getFragments()[0].string();
                esPojo.setSkuTitle(skuTitleValue);
            }
            return esPojo;
        }).collect(Collectors.toList());
        //返回的所有商品
        vo.setProducts(esPojos);

        //聚合信息
        ParsedLongTerms brandAgg = resp.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
        List<SearchVO.BrandsVO> brandsVOS = brandAggBuckets.stream().map(bucket -> {
            SearchVO.BrandsVO brandsVO = new SearchVO.BrandsVO();
            //得到品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
            brandsVO.setBrandId(brandId);

            //得到品牌名字
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandsVO.setBrandName(brandName);

            //3、得到品牌的图片
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandsVO.setBrandImg(brandImg);

            return brandsVO;
        }).collect(Collectors.toList());

        //封装品牌信息
        vo.setBrands(brandsVOS);

        ParsedLongTerms catalogAgg = resp.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> catalogAggBuckets = catalogAgg.getBuckets();
        List<SearchVO.CatalogsVO> catalogsVOS = catalogAggBuckets.stream().map(bucket -> {
            SearchVO.CatalogsVO catalogsVO = new SearchVO.CatalogsVO();
            //得到分类ID
            //得到品牌id
            long catelogId = bucket.getKeyAsNumber().longValue();
            catalogsVO.setCatalogId(catelogId);

            //得到品牌名称
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogsVO.setCatalogName(catalogName);

            return catalogsVO;
        }).collect(Collectors.toList());

        //封装分类信息
        vo.setCatalogs(catalogsVOS);



        ParsedNested attrsAgg = resp.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrsAgg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attrsAggBuckets = attrIdAgg.getBuckets();
        List<SearchVO.AttrsVo> attrsVoList = attrsAggBuckets.stream().map(bucket -> {
            SearchVO.AttrsVo attrsVo = new SearchVO.AttrsVo();

            //属性ID
            long attrId = bucket.getKeyAsNumber().longValue();
            attrsVo.setAttrId(attrId);

            //属性名称
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            attrsVo.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());

            //属性值
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attrValueAgg.getBuckets().stream().map(item -> item.getKeyAsString()).collect(Collectors.toList());
            attrsVo.setAttrValue(attrValues);

            return attrsVo;
        }).collect(Collectors.toList());


        //封装属性信息
        vo.setAttrs(attrsVoList);

        //封装分页参数
        vo.setPageNum(searchDTO.getPageNum());

        int total = (int) resp.getHits().getTotalHits().value;
        vo.setTotal(total);

        int totalPages = (int)total % ESConstants.PRODUCT_PAGESIZE == 0 ?
                (int)total / ESConstants.PRODUCT_PAGESIZE : ((int)total / ESConstants.PRODUCT_PAGESIZE + 1);
        vo.setTotalPages(totalPages);




        return vo;
    }

    private SearchRequest getSearchRequest(SearchDTO searchDTO) {

        // 构建查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // Bool查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 模糊匹配 skuTitle
        this.likeSearch(searchDTO, boolQuery);
        //过滤查询
        this.filter(searchDTO, boolQuery, searchSourceBuilder);
        //分页高亮排序
        this.sortPageAndHighlight(searchDTO, searchSourceBuilder);
        //对搜索的结果进行聚合分析
        this.termsAggregation(searchSourceBuilder);
        //测试 打印构建结果
        String s = searchSourceBuilder.toString();
        System.out.println("构建的 DSL" + s);

        //创建搜索请求
        SearchRequest searchRequest = new SearchRequest(new
                String[]{ESConstants.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;
    }

    private void likeSearch(SearchDTO searchDTO, BoolQueryBuilder boolQuery) {
        String keyword = searchDTO.getKeyword();
        if (StringUtils.isNotBlank(keyword)) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", keyword));
        }
    }

    private void termsAggregation(SearchSourceBuilder searchSourceBuilder) {
        /**
         * 聚合分析
         */
        //1、品牌聚合
        TermsAggregationBuilder brand_agg =
                AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        /*
        1、聚合 brand
         */
        searchSourceBuilder.aggregation(brand_agg);


        //2、分类聚合 catalog_agg
        TermsAggregationBuilder catalog_agg =
                AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg"
        ).field("catalogName").size(1));

        /*
        2、聚合 catalog
         */
        searchSourceBuilder.aggregation(catalog_agg);


        //3、属性聚合 attr_agg
        NestedAggregationBuilder attr_agg =
                AggregationBuilders.nested("attr_agg", "attrs");
        //聚合出当前所有的 attrId
        TermsAggregationBuilder attr_id_agg =
                AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //聚合分析出当前 attr_id 对应的名字
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //聚合分析出当前 attr_id 对应的所有可能的属性值 attrValue
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").
                field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);

        /*
        3、聚合 attr
         */
        searchSourceBuilder.aggregation(attr_agg);
    }

    private void sortPageAndHighlight(SearchDTO searchDTO, SearchSourceBuilder searchSourceBuilder) {
        //排序
        //sort=hotScore_asc/desc
        String sort = searchDTO.getSort();
        if (StringUtils.isNotBlank(sort)) {
            String sortStr = sort.split("_")[1];
            SortOrder order = sortStr.equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(sort.split("_")[0], order);
        }

        //分页
        searchSourceBuilder.from((searchDTO.getPageNum() - 1) *
                ESConstants.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(ESConstants.PRODUCT_PAGESIZE);

        //2.3、高亮
        if (!StringUtils.isEmpty(searchDTO.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            searchSourceBuilder.highlighter(builder);
        }
    }

    private void filter(SearchDTO searchDTO, BoolQueryBuilder boolQuery, SearchSourceBuilder searchSourceBuilder) {
        // catalogId 查询
        Long catalog3Id = searchDTO.getCatalog3Id();
        if (!ObjectUtils.isEmpty(catalog3Id)) {
            boolQuery.filter(QueryBuilders.termsQuery("catalogId", new long[]{catalog3Id}));
        }

        //bool - filter - 按照品牌 id 查询
        List<Long> brandId = searchDTO.getBrandId();
        if (!CollectionUtils.isEmpty(brandId)) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId",
                    brandId));
        }

        //bool - filter - 按照所有指定的属性进行查询
        List<String> attrs = searchDTO.getAttrs();
        if (!CollectionUtils.isEmpty(attrs)) {
            BoolQueryBuilder nestedboolQuery = QueryBuilders.boolQuery();
            //进行处理
            //attr=1_5寸:8寸
            for (String attr : attrs) {
                String attrId = attr.split("_")[0];
                String value = attr.split("_")[1];
//                String[] attrValues = s.split(":");

                nestedboolQuery.must(QueryBuilders.termQuery("attrs.attrId",
                        attrId));
                nestedboolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",
                        value));

                //每一个必须都得生成一个 nested 查询
                NestedQueryBuilder nestedQuery =
                        QueryBuilders.nestedQuery("attrs", nestedboolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }

        //bool - filter - 按照库存是否有进行查询
        if (searchDTO.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock",
                    searchDTO.getHasStock() == 1));
        }

        //1.2、bool - filter - 按照价格区间
        if (!StringUtils.isEmpty(searchDTO.getSkuPrice())) {
            //1_500/_500/500_
            /**
             * "range": {
             * "skuPrice": {
             * "gte": 0,
             * "lte": 6000
             * }
             * }
             */
            RangeQueryBuilder rangeQuery =
                    QueryBuilders.rangeQuery("skuPrice");
            String[] s = searchDTO.getSkuPrice().split("_");
            if (s.length == 2) {
                //区间
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                if (searchDTO.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
                if (searchDTO.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        //把以前的所有条件都拿来进行封装
        searchSourceBuilder.query(boolQuery);
    }
}
